import {IState,ITodo,TODO_STATUS} from '@/typings';
import {useStore,Store} from 'vuex';
import {SET_TODO,SET_TODO_LIST,REMOVE_TODO,SET_TODO_STATUS,SET_TODO_DOING} from '@/store/actionType'
import {watch} from 'vue'

export interface IUseTodo{
	setTodo: (value: string) => void;
	setTodoList: () => void;
	removeTodo: (id:number) => void;
	setStatus: (id:number) => void;
	setDoing: (id:number) => void;
}

interface IUseLocalStorage{
	 getLocalList:() => ITodo[];
	 setLocalList:(todoList:ITodo[]) => void;
}
function useTodo():IUseTodo{
	
	const store:Store<any> = useStore();
	const{setLocalList,getLocalList} = useLocalStorage();
	//从本地初始化list
	const todoList :ITodo[] = getLocalList();
	
	watch(()=>store.state.list,(todoList)=>{
		setLocalList(todoList);
	})
	
	function setTodo(value:string):void{
		const todo: ITodo ={
			//id 用时间戳
			id: new Date().getTime(),
			content:value,
			status:TODO_STATUS.WILLDO
		}
		//更新localList
		
		// setLocalList(todoListNew);
		//发送
		store.dispatch(SET_TODO,todo);
	}
	
	function setTodoList():void{
			store.dispatch(SET_TODO_LIST,todoList);
	}
	
	function removeTodo(id:number):void{
		store.dispatch(REMOVE_TODO,id);
		// setLocalList(store.state.list);
	}
	function setStatus(id:number):void{
		store.dispatch(SET_TODO_STATUS,id);
		// setLocalList(store.state.list);
	}
	
	function setDoing(id:number):void{
		store.dispatch(SET_TODO_DOING,id);
		// setLocalList(store.state.list);
	}
	
	
	//返回功能集合
	return{
		setTodo,//组成ITodo,并传到action的 SET_TODO方法
		setTodoList,//组件onmounted时调用
		removeTodo,
		setStatus,
		setDoing,
		
	}
}

//储存在本地
function useLocalStorage ():IUseLocalStorage{
	function getLocalList():ITodo[]{
		return JSON.parse(localStorage.getItem('todoList')||'[]')
	}
	function setLocalList(todoList:ITodo[]):void{
		return localStorage.setItem('todoList',JSON.stringify(todoList))
	}
	return{
		getLocalList,
		setLocalList,
	}
}

export {
	useTodo
}